import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/commom/Dio.dart';
import 'package:flutter_app/commom/Global.dart';
import 'package:flutter_app/widgets/HYSizeFit.dart';
import 'package:flutter_app/widgets/ModifyUserResultCard.dart';
import 'package:flutter_app/widgets/ReleasePjResultCard.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'ChoosePjType.dart';
import 'ProjectInfo.dart';
import 'ReleasePjRoute.dart';

class WaitingPage extends StatefulWidget{
  const  WaitingPage({
    Key key,
  }) : super(key: key);
  @override
  _WaitingPageState createState() => _WaitingPageState();
}
class _WaitingPageState extends State<WaitingPage> {

  _WaitingPageState();
  Future<String> _loadingFuture;

  @override
  void initState() {
    super.initState();
    _loadingFuture = loadingDataFunction();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<String>(
        //future：这个参数需要一个Future 对象，类似于 网络请求、IO
        future: _loadingFuture,
        ///这里的数据格式与上述FutureBuilder设置的泛型格式一至
        initialData: "初始化的数据",
        ///构建显示的 Widget  会根据加载的状态来多次回调些方法
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          //加载状态判断
          switch (snapshot.connectionState) {

          ///可理解为初始加载显示的 Widget 异步加载开始时的回调
            case ConnectionState.none:
              return  Text('Result: ${snapshot.data}');
          ///异步加载中的回调
            case ConnectionState.active:
            case ConnectionState.waiting:
              return SpinKitRotatingPlain(
                color: Colors.black54,
              );
          ///异步加载完成的回调
            case ConnectionState.done:
            //判断是否加载失败
              if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                ///通过 [snapshot.data]来获取异步加载的数据
                return FriendCircleRoute();
              }
          }
          return null;
        },
      ),
    );
  }

  ///模拟耗时的网络请求
  Future<String> loadingDataFunction() async {
    Global.matchingFriend = await EA(context).matchingFriend();
  }
///模拟
}

class FriendCircleRoute extends StatefulWidget {
  FriendCircleRoute({Key key}) : super(key: key);
  @override
  FriendCircleRouteState createState() => FriendCircleRouteState();
}

class FriendCircleRouteState extends State<FriendCircleRoute> {
  //int _selectedIndex = 1;
  bool isLoading = true;

  Widget _item_CardBuilder(BuildContext context, int position) {
    return Container(
        margin: EdgeInsets.only(top: HYSizeFit.setPx(10)),
        child: Padding(
          padding: EdgeInsets.only(top: 0),
          child: OutlinedButton(
            style: ButtonStyle(
              shape: MaterialStateProperty.resolveWith<OutlinedBorder>((_) {
                return RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10));
              }),
              backgroundColor:
                  MaterialStateProperty.resolveWith<Color>((states) {
                if (states.contains(MaterialState.disabled)) {
                  return Colors.grey[100];
                }
                return Colors.white;
              }),
              side: MaterialStateProperty.resolveWith((states) {
                return BorderSide(color: Colors.black38, width: 1);
              }),
            ),
            child: IntrinsicHeight(
              child: Column(
                //direction: Axis.vertical,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(top: HYSizeFit.setPx(5)),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: EdgeInsets.only(top: HYSizeFit.setPx(10)),
                          child: ClipRect(
                            child: Image.asset(
                              "imgs/激光打印机.jpg",
                              width: HYSizeFit.setPx(50),
                            ),
                          ),
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: EdgeInsets.only(
                                  top: HYSizeFit.setPx(5),
                                  left: HYSizeFit.setPx(15)),
                              child: Text(
                                Global.matchingFriend.projects[position]
                                    ['project']['pjName'],
                                style: TextStyle(
                                    color: Colors.black87,
                                    fontSize: HYSizeFit.setPx(22),
                                    fontWeight: FontWeight.w700
                                    //background: new Paint()..color = Colors.yellow,
                                    ),
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.only(
                                  top: HYSizeFit.setPx(5),
                                  left: HYSizeFit.setPx(12)),
                              child: Text(
                                Global.matchingFriend.projects[position]
                                    ['owner']['usrName'],
                                style: TextStyle(
                                    color: Colors.black54,
                                    fontSize: HYSizeFit.setPx(15),
                                    fontWeight: FontWeight.w500
                                    //background: new Paint()..color = Colors.yellow,
                                    ),
                              ),
                            ),
                            Padding(
                                padding: EdgeInsets.only(
                                    top: HYSizeFit.setPx(5),
                                    left: HYSizeFit.setPx(12)),
                                child: Container(
                                  width: HYSizeFit.setPx(250),
                                  child: Text(
                                    Global.matchingFriend.projects[position]
                                                ['project']['pjNote'] !=
                                            null
                                        ? Global.matchingFriend
                                                .projects[position]['owner']
                                            ['usrName']
                                        : "最近有搞机加工的朋友吗，本公司急需，价格可以面谈！！",
                                    softWrap: true,
                                    maxLines: 2,
                                    style: TextStyle(
                                        color: Colors.black,
                                        fontSize: HYSizeFit.setPx(15),
                                        fontWeight: FontWeight.w500
                                        //background: new Paint()..color = Colors.yellow,
                                        ),
                                  ),
                                )),
                          ],
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: HYSizeFit.setPx(15)),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Text(
                          "发布日期：" +
                              formatDate(
                                  Global.matchingFriend.projects[position]
                                      ['project']['pjReltime'],
                                  [yyyy, '-', mm, '-', dd]),
                          softWrap: true,
                          style: TextStyle(
                              color: Colors.black54,
                              fontSize: HYSizeFit.setPx(10),
                              fontWeight: FontWeight.w300
                              //background: new Paint()..color = Colors.yellow,
                              ),
                        ),
                        Text(
                          "         截止日期：" +
                              formatDate(
                                  Global.matchingFriend.projects[position]
                                      ['project']['pjDeltime'],
                                  [yyyy, '-', mm, '-', dd]),
                          softWrap: true,
                          style: TextStyle(
                              color: Colors.black54,
                              fontSize: HYSizeFit.setPx(10),
                              fontWeight: FontWeight.w300
                              //background: new Paint()..color = Colors.yellow,
                              ),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                      padding: EdgeInsets.only(top: HYSizeFit.setPx(5)),
                      child: Container(
                        width: HYSizeFit.setPx(355),
                        height: HYSizeFit.setPx(30),
                        child: OverflowBox(
                          maxWidth: HYSizeFit.setPx(355),
                          maxHeight: HYSizeFit.setPx(30),
                          child: Container(
                              decoration: new BoxDecoration(
                                //border: new Border.all(color: Colors.black12, width: 0.5), // 边色与边宽度
                                color: Colors.black12, // 底色
                                borderRadius: BorderRadius.all(Radius.circular(10.0)), // 也可控件一边圆角大小
                                //borderRadius: new BorderRadius.vertical(top: Radius.elliptical(20, 60)),
                              ),
                              child: Padding(
                                padding: EdgeInsets.only(
                                    right: HYSizeFit.setPx(10),
                                    left: HYSizeFit.setPx(10)),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                    Text("该订单中您可能对这些业务感兴趣：",
                                      softWrap: true,
                                      style: TextStyle(
                                          color: Colors.black38,
                                          fontSize: HYSizeFit.setPx(12),
                                          fontWeight: FontWeight.w300
                                        //background: new Paint()..color = Colors.yellow,
                                      ),
                                    ),
                                    Expanded(
                                        child: Wrap(
                                          children: Global.matchingFriend.projects[position]['project']['show'].map<Widget>((item) => Card(
                                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
                                            elevation: 0,
                                            child: Padding(
                                              padding: EdgeInsets.all(HYSizeFit.setPx(2)),
                                              child: Text(
                                                item,
                                                textAlign: TextAlign.end,
                                                style: TextStyle(
                                                    color: Colors.black54,
                                                    fontSize: HYSizeFit.setPx(12),
                                                    fontWeight: FontWeight.w300
                                                  //background: new Paint()..color = Colors.yellow,
                                                ),
                                              ),
                                            ),
                                            color: Colors.white,
                                            //onPressed: (){},
                                          )).toList(),
                                        )
                                        ),
                                  ],
                                ),
                              )),
                        ),
                      )
                      ),
                ],
              ),
            ),
            onPressed: () => {
              Navigator.push(
                context,
                new MaterialPageRoute(builder: (context) {
                  return new ProjectInfo(index: position, flag: 1);
                }),
              )
            },
          ),
        ));
  }

  @override
  void initState() {}

  @override
  Widget build(BuildContext context) {
    HYSizeFit.initialize(context);
    return Scaffold(
      //backgroundColor: Color.fromRGBO(239, 239, 239, 1),
      appBar: AppBar(
        title: Text(''),
        actions: <Widget>[
          //导航栏右侧菜单
          IconButton(
            icon: Icon(Icons.add, color: Colors.black),
            onPressed: () async {
              if(Global.UserInfo) {
                Navigator.push(
                  context,
                  new MaterialPageRoute(builder: (context) {
                    //return new ProjectEdit();
                    return new ChoosePjTypeRoute();
                  }),
                );
              }
              else await NotifiedCard(context);

            },
          )
        ],
        leading: Builder(builder: (context) {
          return IconButton(
              icon:
                  Icon(Icons.chat_bubble_outline, color: Colors.black), //自定义图标
              onPressed: () {});
        }),
      ),
      body: RefreshIndicator(
        onRefresh: _onRefresh,
        child: ListView.builder(
            padding: EdgeInsets.fromLTRB(
                HYSizeFit.setPx(10), 0, HYSizeFit.setPx(10), 0),
            scrollDirection: Axis.vertical,
            itemCount: (Global.matchingFriend.projects == null)
                ? 0
                : Global.matchingFriend.projects.length,
            //itemExtent: HYSizeFit.setPx(190),
            shrinkWrap: true,
            physics: const AlwaysScrollableScrollPhysics(),
            //列表项构造器
            itemBuilder: _item_CardBuilder),
      )

    );
  }
  Future<Null> _onRefresh()  async{
    Global.matchingFriend.projects.clear();
    setState(() {
      isLoading = true;
    });
    _onRefreshData();
  }
  void _onRefreshData() async{
    if(isLoading){
      Global.matchingFriend = await EA(context).matchingFriend();
      setState(() {
        isLoading = false;
      });
    }
  }
}
